/*
 * Copyright (C) 2021 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.xuexiang.xuidemo.fragment.zhuanquanquan;

import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.core.content.ContextCompat;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xaop.cache.XMemoryCache;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.grouplist.XUICommonListItemView;
import com.xuexiang.xui.widget.grouplist.XUIGroupListView;
import com.xuexiang.xuidemo.DemoDataProvider;
import com.xuexiang.xuidemo.R;
import com.xuexiang.xuidemo.activity.MainActivity;
import com.xuexiang.xuidemo.adapter.SimpleRecyclerAdapter;
import com.xuexiang.xuidemo.base.BaseFragment;
import com.xuexiang.xuidemo.entity.Decision;
import com.xuexiang.xuidemo.fragment.AboutFragment;
import com.xuexiang.xuidemo.utils.XToastUtils;
import com.xuexiang.xuidemo.utils.ZhuanpanSPUtils;
import com.yanzhenjie.recyclerview.OnItemClickListener;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

@Page(name = "我的决定",anim = CoreAnim.slide)
public class DecisionFragment extends BaseFragment {

    ZhuanpanSPUtils zInstance = ZhuanpanSPUtils.getInstance();
    List<Decision> decisions;
    List<String> title;

    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    private SimpleRecyclerAdapter mAdapter;

    @BindView(R.id.recycler_view)
    SwipeRecyclerView recyclerView;

    @Override
    protected TitleBar initTitle() {
        TitleBar titleBar = super.initTitle();
        titleBar.addAction(new TitleBar.ImageAction(R.drawable.add) {
            @Override
            @SingleClick
            public void performAction(View view) {
                openNewPage(AddDecisionFragment.class);
            }
        });
        return titleBar;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.layout_swipe_recycler_view;
    }

    @Override
    protected void initViews() {
        decisions = zInstance.getAllDecision();
        title = new ArrayList<>();
        for(int i=0;i<decisions.size();i++) {
            title.add(decisions.get(i).getTitle());
        }
        WidgetUtils.initRecyclerView(recyclerView);

        //必须在setAdapter之前调用
        recyclerView.setSwipeMenuCreator(swipeMenuCreator);
        //必须在setAdapter之前调用
        recyclerView.setOnItemMenuClickListener(mMenuItemClickListener);
        recyclerView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int adapterPosition) {
                zInstance.setChoice(decisions.get(adapterPosition).getId());
                popToBack();
            }
        });
        recyclerView.setAdapter(mAdapter = new SimpleRecyclerAdapter(title,decisions));

        refreshLayout.setColorSchemeColors(0xff0099cc, 0xffff4444, 0xff669900, 0xffaa66cc, 0xffff8800);
    }

    private SwipeMenuCreator swipeMenuCreator = (swipeLeftMenu, swipeRightMenu, position) -> {
        int width = getResources().getDimensionPixelSize(R.dimen.dp_70);

        // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
        // 2. 指定具体的高，比如80;
        // 3. WRAP_CONTENT，自身高度，不推荐;
        int height = ViewGroup.LayoutParams.MATCH_PARENT;

        // 添加左侧的，如果不添加，则左侧不会出现菜单。

        // 添加右侧的，如果不添加，则右侧不会出现菜单。
        {
            SwipeMenuItem addItem = new SwipeMenuItem(getContext()).setBackground(R.drawable.menu_selector_green)
                    //.setImage(R.drawable.modify)
                    .setText("修改")
                    .setTextColor(Color.WHITE)
                    .setWidth(width)
                    .setHeight(height);
            swipeRightMenu.addMenuItem(addItem); // 添加菜单到右侧。

            SwipeMenuItem deleteItem = new SwipeMenuItem(getContext()).setBackground(R.drawable.menu_selector_red)
                    //.setImage(R.drawable.ic_swipe_menu_delete)
                    .setText("删除")
                    .setTextColor(Color.WHITE)
                    .setWidth(width)
                    .setHeight(height);
            swipeRightMenu.addMenuItem(deleteItem);// 添加菜单到右侧。
        }
    };

    @Override
    protected void initPage() {
        super.initPage();
    }

    /**
     * RecyclerView的Item的Menu点击监听。
     */
    private OnItemMenuClickListener mMenuItemClickListener = (menuBridge, position) -> {
        menuBridge.closeMenu();

        int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
        int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。

        if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {
            if(menuPosition == 0) {
                openPage(SetDecisionFragment.class,"key",decisions.get(position).getId());
            }
            else {
                zInstance.deleteDecision(decisions.get(position).getId());
                decisions.remove(position);
                title.remove(position);
                mAdapter.notifyDataSetChanged();
            }
        } else if (direction == SwipeRecyclerView.LEFT_DIRECTION) {
            //XToastUtils.toast("list第" + position + "; 左侧菜单第" + menuPosition);
        }
    };

    @Override
    protected void initListeners() {
        //下拉刷新
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(() -> {
                    //Toast.makeText(getContext(),"刷新",Toast.LENGTH_SHORT).show();
                    List<Decision> newDecisions = zInstance.getAllDecision();
                    decisions.clear();
                    title.clear();
                    for(int i=0;i<newDecisions.size();i++) {
                        decisions.add(newDecisions.get(i));
                        title.add(newDecisions.get(i).getTitle());
                    }
                    mAdapter.notifyDataSetChanged();
                    if (refreshLayout != null) {
                        refreshLayout.setRefreshing(false);
                    }
                }, 1000);
            }
        });
        //loadData();
    }

    private void loadData() {
        new Handler().postDelayed(() -> {
            //Toast.makeText(getContext(),"刷新",Toast.LENGTH_SHORT).show();
            List<Decision> newDecisions = zInstance.getAllDecision();
            decisions.clear();
            title.clear();
            for(int i=0;i<newDecisions.size();i++) {
                decisions.add(newDecisions.get(i));
                title.add(newDecisions.get(i).getTitle());
            }
            mAdapter.notifyDataSetChanged();
            if (refreshLayout != null) {
                refreshLayout.setRefreshing(false);
            }
        }, 1000);
    }
}
